package org.springframework.boot.netty.support;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * Author: huoxingzhi
 * Date: 2020/12/25
 * Email: hxz_798561819@163.com
 */
public class PathMatchWrapper {

    private static PathMatcher pathMatcher = new AntPathMatcher();

    public static boolean isMatch(String pattern, String path){
        return pathMatcher.match(pattern,path);
    }

    private static List<String> getCandidateMatches(Set<String> patterns,String path){
        List<String> matches = patterns.stream().filter(pattern -> {
            return isMatch(pattern, path);
        }).collect(Collectors.toList());
        return matches;
    }


    /**
     * 路径最长优先
     * @param patterns
     * @param path
     * @return
     */
    public static String getBestMath(Set<String> patterns,String path){
        List<String> candidateMatches = getCandidateMatches(patterns,path);
        Comparator<String> patternComparator = pathMatcher.getPatternComparator(path);
        String bestMath = null;
        if(!CollectionUtils.isEmpty(candidateMatches)){
            candidateMatches.sort(patternComparator);
            return candidateMatches.get(0);
        }
        return null;
    }


    public static Map<String,String> extractUriTemplateVariables(String pattern, String path){
        return pathMatcher.extractUriTemplateVariables(pattern,path);
    }

}
